import BackPage from '@/components/BackPage';
import SelectOne from '@/components/SelectOne';
import { getAllCoupons } from '@/services/coupons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button } from 'antd';
import moment from 'moment';
import { useCallback, useEffect, useRef, useState } from 'react';
import CreateNew from './components/CreateNew';
import { HOWMUCH } from './constants';
import styles from './index.less';

const Preferential: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [createNew, setCreateNew] = useState<boolean>(false);
  const [selectList, setSelectList] = useState<any[]>([]);
  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);

  // 分页的方法
  const handlePageChange = (page: any) => {
    setCurrentPage(page);
  };

  const getList = useCallback(async () => {
    try {
      const res = await getAllCoupons({ pageIndex: currentPage });
      setTotal(res.total);
      setList(res.list);
    } catch (error) {
      console.error(error);
    }
  }, [currentPage]);

  useEffect(() => {
    getList();
  }, [getList]);

  const columns: ProColumns<any>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '优惠券编号',
      dataIndex: 'id',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '活动名称',
      dataIndex: 'name',
      ellipsis: true,
      // render: (_, record) => {
      //   console.log(record);
      // },
    },
    {
      title: '优惠力度',
      dataIndex: 'efforts',
      ellipsis: true,
      render: (text, record) => [
        <div key={record.id}>
          {HOWMUCH.map((item: any) => {
            if (record.efforts === item.key) {
              return item.value;
            }
          })}
        </div>,
      ],
    },
    {
      title: '起止时间',
      key: 'date',
      dataIndex: 'date',
      valueType: 'date',
      render: (text, record) => [
        <div key={record.id}>
          {`${moment(Number(record.timeStart)).format('YYYY-MM-DD HH:mm:ss')}`}
          <br />
          {`-`}
          <br />
          {`${moment(Number(record.timeEnd)).format('YYYY-MM-DD HH:mm:ss')}`}
        </div>,
      ],
    },
    {
      disable: true,
      title: '状态',
      dataIndex: 'ifDelete',
      filters: true,
      onFilter: true,
      ellipsis: true,
      valueType: 'select',
      valueEnum: {
        all: { text: '超长'.repeat(50) },
        '2': {
          text: '活动未开始',
          status: 'Error',
          disabled: true,
        },
        '1': {
          text: '已下架',
          status: 'Error',
        },
        '0': {
          text: '活动进行中',
          status: 'Success',
          disabled: true,
        },
      },
    },
  ];

  return (
    <BackPage thisRoute={'/preferential'} lastRoute={'优惠活动'}>
      <div className={styles.container}>
        <SelectOne
          searchText={'优惠券编号'}
          fromWhere={'pre'}
          selected={(value) => {
            setSelectList(value);
          }}
          currentPage={currentPage}
          clear={() => {
            setSelectList([]);
          }}
        />
        <ProTable<any>
          columns={columns}
          actionRef={actionRef}
          cardBordered={false}
          dataSource={selectList.length !== 0 ? selectList : list}
          editable={{
            type: 'multiple',
          }}
          rowKey="id"
          search={false}
          options={false}
          form={{
            // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
            syncToUrl: (values, type) => {
              if (type === 'get') {
                return {
                  ...values,
                  created_at: [values.startTime, values.endTime],
                };
              }
              return values;
            },
          }}
          pagination={{
            total,
            current: currentPage, // 当前页数
            pageSize: 10, // 每页条数
            size: 'small', // 分页的样式
            hideOnSinglePage: true, // 只有一页时是否隐藏分页器
            onChange: handlePageChange, // 分页的方法
          }}
          dateFormatter="string"
          headerTitle=""
        />
        <Button
          className={styles.newbtn}
          onClick={() => {
            setCreateNew(true);
          }}
        >
          新建优惠券
        </Button>
        <CreateNew
          visible={createNew}
          handleCancel={() => {
            setCreateNew(false);
          }}
          getList={getList}
        />
      </div>
    </BackPage>
  );
};
export default Preferential;
